<template>
  <form-dialop
    :title="$t('common.Create')"
    :visible="visible"
    width="50%"
    @handleClose="handleClose"
		v-loading="loading"
  >
    <template #content>
      <el-form ref="form" :model="formData" label-position="right" label-width="100px" :rules="formRule">
        <el-form-item :label="$t('systemBack.version')" prop="title" name="title">
          <el-input v-model="formData.title" style="width: 206px" @keyup.enter.native="submit"></el-input>
        </el-form-item>
        <el-form-item :label="$t('systemBack.releaseDate')" label-position="right" label-width="100px" prop="date" name="date">
          <el-date-picker style="width: 206px" v-model="formData.date" type="date" :placeholder="$t('systemBack.selectDate')" @keyup.enter.native="submit"></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('common.description')" prop="descriptions" label-position="right" label-width="100px" style="align-items: unset !important">
          <div id="markdown" ref="markdown"></div>
        </el-form-item>
      </el-form>

    </template>
    <template #footer>
      <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submit" :disabled="loading">{{ $t('common.confirm') }}</el-button>
    </template>
  </form-dialop>
</template>
<script lang="ts">
import Vue from 'vue'
import FormDialop from '@/components/Dialog/formDialog.vue';
import E from 'wangeditor';
import sparkMd5 from 'spark-md5'
export default Vue.extend({
  components: {
    FormDialop
  },
  props: {
    createMethod: {
      type: Function,
      default() {
        return () => Promise.resolve();
      }
    }
  },
  data() {
    const validateGetVersion = (rule: any,value: any,callback: any) => {
      let exp = /^([1-9]\d|[1-9])(\.([1-9]\d|\d)){2}$/
      if(!exp.test(value)){
        return callback(new Error(this.$t("clientVersionLog.versionTitleTips").toString()))
      }
      this.$pandaApi.apiGetVersionsDetail({ product_model: this.$route.query.product_model }).then((res: any)=>{
        const index = res.findIndex((versionDetail: any) => versionDetail.version_number == "v" + this.formData.title);
        if (index == -1) {
          callback()
        } else {
          callback(new Error(this.$t("clientVersionLog.getVersionError").toString()))
        }
      })
    }

    const validateGetDescriptions = (rule: any,value: any,callback: any) => {
      if((this as any).ed.txt.html() == ""){
        return callback (new Error(this.$t("clientVersionLog.descriptionTip").toString()))
      } else {
        callback();
      }
    } 

    return {
      visible: false,
      loading: false,
      formData: {
        title: '',
        date: '',
        descriptions:''
      },
      ed: '',
      htmlData: '',
      formRule: {
        title:[
          { required: true, message: this.$t('clientVersionLog.VersionTitleTipsError'), trigger: 'blur' },
          { validator: validateGetVersion, trigger: 'blur'}
        ],
        date:[
          {type:"date",required:true,message:this.$t('clientVersionLog.createDateTip'),tigger:'blur'}
        ],
        descriptions:[
          {validator: validateGetDescriptions,required: true,tigger:'blur'}
        ]
      }
    }
  },
  methods: {
    initMD() {
      (this as any).ed = new E('#markdown');
      (this as any).ed.config.showFullScreen = false;
      (this as any).ed.config.menus = ['head','bold','fontName','fontSize','italic','underline','strikeThrough','indent','lineHeight','foreColor','backColor','link','list','todo','justify','quote','image','table','code','splitLine','undo','redo'];
      (this as any).ed.config.uploadImgServer = '/panda/faq/image/update';
      const that = this;
      (this as any).ed.config.customUploadImg = (resultFiles: any, insertImgFn: any) => {
        const fileReader = new FileReader()
        fileReader.readAsBinaryString(resultFiles[0]);
        fileReader.onload = (e: any) => {
          const md5 = sparkMd5.hashBinary(e.target.result);
          const headers = {
            "markdown-md5": md5,
            "Content-Disposition": "attachment;filename=" + encodeURIComponent(resultFiles[0].name),
            "Content-Type": "application/json"
          };
          that.$pandaApi.apiUploadImgs(resultFiles[0], headers).then((res: any) => {
            if(res.errno == 0 && res.data.length > 0) {
              insertImgFn(res.data[0].url);
            }
          }).catch((err: any)=>{
            console.log(err)
          })
        }
      };
      (this as any).ed.create();
      
    },
    init() {
      (this as any).tenant_options = [];
			(this as any).formData = {
					title: ""
			};

      (this as any).$nextTick(() => {
        if(!this.ed)
          this.initMD()
        if (this.$refs['form']) {
          (this.$refs['form'] as any).clearValidate();
        }
      })
      this.visible = true;
    },
    submit() {
      (this.$refs.form as any).validate((valid: any) => {
        if (valid) {
          if(!(this as any).ed.txt.html()) {
            this.$message.warning((this as any).$t('markdowns.contentTips'))
            return ;
          }
					this.loading = true;
          const data: any = {
            "version_number": this.formData.title,
            "content": (this as any).ed.txt.html(),
            "product_model": this.$route.query.product_model,
            "created_at": this.formData.date
          };
          this.$pandaApi.apiCreateVersion(data).then((res: any) => {
            if(res.code == 400) {
              (this as any).$message.error((this as any).$t('markdowns.createFail'));
              (this as any).handleClose();
            } else {
              this.$message.success((this as any).$t('markdowns.createSuccess'));
              (this as any).handleClose();
              this.$emit("success");
            }
          })
        }
      });
    },
    handleClose() {
      (this as any).formData = {
        title: "",
        descriptions: ""
      };
      (this as any).ed.txt.clear();
      this.visible = false;
			this.loading = false;
    }
  }
})
</script>
<style scoped>
#markdown {
  width: 120%;
}
</style>
